import {auth, getUserInfo} from "@/services/api";
import {ActionTree} from "vuex";
import {State} from "./state";
import i18n from "@/locales";

const actions: ActionTree<State, any> = {
    async loginWechat({commit, state}) {
        await uni.showLoading({
            title: "登录中...",
        });
        commit("loading", true);
        const _this = this;
        return await new Promise(async (resolve, reject) => {
            try {
                uni.login({
                    "provider": "weixin",
                    "onlyAuthorize": true, // 微信登录仅请求授权认证
                    success: async function (event) {
                        const {code} = event
                        //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
                        const resp: any = await auth({code, xuser: 0});
                        commit("loading", false);
                        uni.hideLoading();
                        if (resp != null) {
                            commit("login", resp);
                            resolve(resp)
                            return
                        }
                        resolve(resp)
                    },
                    fail: function (err) {
                        // 登录授权失败
                        // err.code是错误码
                        uni.hideLoading();
                        commit("loading", false);
                    }
                })
            } catch (err) {
                uni.hideLoading();
                commit("loading", false);
                reject(err);
            }
        });
    },

    async logout({commit, state}) {
        commit('logout');
    },

    async account({commit}) {
        const res = await getUserInfo();
        commit('setUserInfo', res);
    },
    setLang({commit}, payload: any) {
        if (!payload) return;
        uni.setStorageSync('language', payload)
        i18n.locale = payload;
        commit("updateLang", payload);
    },
};

export default actions;
